#include "AuthService.h"
#include "../ServerStruct.h"
#include "../common/YXJwt.h"
#include "../common/YXLog.h"
#include "../common/YXResult.h"
#include "../constant/AuthConstant.h"
#include "../mapper/AuthMapper.h"

YXResult *login(cJSON *jsonObject) {
    const char* err;

    // 获取账号密码
    const cJSON *username = cJSON_GetObjectItemCaseSensitive(jsonObject, "username");
    if (username == NULL) {
        return YXResultUtils.error("账号不能为空！");
    }
    const cJSON *password = cJSON_GetObjectItemCaseSensitive(jsonObject, "password");
    if (password == NULL) {
        return YXResultUtils.error("密码不能为空！");
    }
    int userId = 0;
    // 特殊处理admin
    if (strcmp(username->valuestring, ADMIN_DEFAULT_USERNAME) == 0) {
        if (strcmp(password->valuestring, ADMIN_DEFAULT_PASSWORD) != 0) {
            return YXResultUtils.error("账号或密码错误！");
        }
    } else {
        // 根据用户名去获取（id和）密码
        MYSQLResult* result = selectIdPasswordByUsername(username->valuestring);
        if (result->type == MYSQL_RESULT_ERROR) {
            err = result->errMsg;
            yxMYSQLResultFree(result);
            return YXResultUtils.error(err);
        }
        yxObject* obj = yxMYSQLResultGetObjectValue(result);
        if (obj == NULL) {
            yxMYSQLResultFree(result);
            return YXResultUtils.error("用户不存在！");
        }
        char* t_password = yxJSONGetObjectStringItem(obj, "password");
        if (strcmp(t_password, password->valuestring) != 0) {
            yxMYSQLResultFree(result);
            return YXResultUtils.error("账号或密码错误！");
        }
        userId = yxJSONGetObjectIntItem(obj, "id");
        yxMYSQLResultFree(result);
    }

    // 生成令牌
    JwtBuilder *jwt_builder = yx_jwt_create();
    yx_jwt_add_claims_int(jwt_builder, "id", 2, userId);
    char *token = yx_jwt_generate(jwt_builder);

    yxObject* tokenObject = cJSON_CreateString(token);
    yx_jwt_free(token);
    return YXResultUtils.successWithMsg("登录成功！", tokenObject);
}